package zhanglinwei.cryptotools.core.source;

import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginLookup;
import zhanglinwei.cryptotools.core.resolver.CryptoablePropertyResolver;
import org.springframework.core.env.PropertySource;

public interface CryptoablePropertySource<T> extends OriginLookup<String> {

    PropertySource<T> getDelegate();

    Object getProperty(String name);

    void refresh();

    default Object resolveProperty(CryptoablePropertyResolver resolver, PropertySource<T> source, String name) {
        Object value = source.getProperty(name);
        if (value instanceof String) {
            String stringValue = String.valueOf(value);
            if (resolver.isEncrypted(stringValue)) {
                return resolver.decrypt(stringValue);
            }
            return stringValue;
        }
        return value;
    }

    @Override
    default Origin getOrigin(String key) {
        if(getDelegate() instanceof OriginLookup) {
            return ((OriginLookup<String>) getDelegate()).getOrigin(key);
        }
        return null;
    }

    @Override
    default boolean isImmutable() {
        if(getDelegate() instanceof OriginLookup) {
            return ((OriginLookup<?>) getDelegate()).isImmutable();
        }
        return OriginLookup.super.isImmutable();
    }

}